import axios from "axios";
import { Message } from "element-ui";
import { ndsdToken } from "@/api/api.js";


const http = axios.create({
  // baseURL: '/mainIp',
  baseURL: "/",
  timeout: 30000,
});


http.interceptors.request.use((config) => {
  console.log("http.interceptors.request===", config);
  const access_token = sessionStorage.getItem("access_token");
  const refresh_token = sessionStorage.getItem("refresh_token");
  config.headers["access-token"] = access_token;
  config.headers["refresh-token"] = refresh_token;
  return config;
});

let requests = [];
let num = 1;
http.interceptors.response.use(
  (config) => {
    console.log("http.interceptors.response===", config);
    if (config.data.code != 0) {
      Message.warning(config.data.message);
    }
    return config;
  },
  (error) => {
    console.log("ndsdToken===", error, error.config, error.response.status);
    const config = error.config;
    requests.push(config);
    if (error.response.status == 401) {
      if (num < 2) {
        num = num + 1;
        ndsdToken().then((res) => {
          if (res.data.code == 0) {
            const access_token = res.data.access_token;
            const refresh_token = res.data.refresh_token;
            console.log(
              "ndsdToken====",
              res,
              requests,
              access_token,
              refresh_token
            );
            config.headers["access-token"] = access_token;
            config.headers["refresh-token"] = refresh_token;
            if(access_token) sessionStorage.setItem("access_token", access_token);
            if(refresh_token)  sessionStorage.setItem("refresh_token", refresh_token);
            location.reload();
            return http(config);
          }
        });
      }
    } else if (error.response.status == 403) {
      window.location.href = "/";
      window.localStorage.removeItem("access-token");
      window.localStorage.removeItem("refresh-token");
    } 
  }
);

export default http;
